﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Hosting;
using System.Web.Http;
using Treasure.Service.DBModel;
using Treasure.Service.Utility;

namespace Treasure.Service.Controllers
{
    public class TreasureController : ApiController
    {
        //private string DBPath = HostingEnvironment.MapPath("~/App_Data/book.db");
        private Logger logger = new Logger(typeof(TreasureController));

        /// <summary>
        /// 菜单树列表
        /// </summary>
        /// <returns></returns>
        [Route("api/treasure/treelist")]
        [HttpGet]
        public HttpResponseMessage GetTreeList()
        {
            this.logger.Info("请求了菜单树列表" );
            HttpResponseMessage result = null;
           
            string listjson= string.Empty;
            try
            {
                using (T_Model mode = new T_Model())
                {
                    
                    var resultContent = from d in mode.Books.ToList()
                    group d by new
                                {
                                    d.ID,
                                    d.b_id,
                                    d.b_name,
                                    d.b_parent_id

                                } into s
                                select new
                                {
                                     s.Key.ID,
                                     s.Key.b_id,
                                     s.Key.b_name,
                                     s.Key.b_parent_id
                                };
                    listjson = Newtonsoft.Json.JsonConvert.SerializeObject(resultContent);
                    result = new HttpResponseMessage(HttpStatusCode.OK);
                    result.Content= new StringContent(listjson, Encoding.UTF8, "text/plain");
                }
            }
            catch (Exception ex)
            {
                this.logger.Error("数据库连接出错：" + ex.Message);
                return new HttpResponseMessage(HttpStatusCode.NotFound);
               
            }
           
            return result;
        }
        /// <summary>
        /// 查找节点 （没有使用）
        /// </summary>
        /// <param name="nodeid"></param>
        /// <returns></returns>

        [Route("api/treasure/findnode")]
        [HttpGet]
        public HttpResponseMessage GetFindNode(int nodeid)
        {
            this.logger.Info("查找ID" + nodeid);
            HttpResponseMessage result = null;
            
            string listjson = string.Empty;
            try
            {
                using (T_Model mode = new T_Model())
                {
                    var books = mode.Books.FirstOrDefault(b=>b.b_id==nodeid);
                    listjson = Newtonsoft.Json.JsonConvert.SerializeObject(books);
                    result = new HttpResponseMessage(HttpStatusCode.OK);
                    result.Content = new StringContent(listjson, Encoding.UTF8, "text/plain");
                }
            }
            catch (Exception ex)
            {
                this.logger.Error("数据库连接出错：" + ex.Message);
                return new HttpResponseMessage(HttpStatusCode.NotFound);

            }

            return result;
        }

        /// <summary>
        /// 目录树最大ID
        /// </summary>
        /// <returns></returns>
        [Route("api/treasure/maxid")]
        [HttpGet]
        public HttpResponseMessage GetMaxID()
        {
            HttpResponseMessage result = null;
            string listjson = string.Empty;
            try
            {
                using (T_Model mode = new T_Model())
                {
                    listjson = mode.Books.Max(b => b.b_id).ToString();
                    result = new HttpResponseMessage(HttpStatusCode.OK);
                    result.Content = new StringContent(listjson, Encoding.UTF8, "text/plain");
                }
            }
            catch (Exception ex)
            {
                this.logger.Error("数据库连接出错：" + ex.Message);
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }

            return result;
        }
        /// <summary>
        /// 根据id查找内容
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [Route("api/treasure/findcontent")]
        [HttpGet]
        public HttpResponseMessage GetFindContent(int id)
        {
            HttpResponseMessage result = null;
            string listjson = string.Empty;
            try
            {
                using (T_Model mode = new T_Model())
                {
                    book _book = mode.Books.FirstOrDefault(b => b.b_id ==id);
                    if (_book != null)
                    {
                        listjson = _book.b_content;
                        result = new HttpResponseMessage(HttpStatusCode.OK);
                        result.Content = new StringContent(listjson, Encoding.UTF8, "text/plain");
                    }
                    else
                    {
                        result = new HttpResponseMessage(HttpStatusCode.OK);
                        result.Content = new StringContent(listjson, Encoding.UTF8, "text/plain");
                    }
                   
                }
            }
            catch (Exception ex)
            {
                this.logger.Error("数据库连接出错：" + ex.Message);
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }

            return result;
        }
        /// <summary>
        /// 新增目录
        /// </summary>
        /// <param name="jsonbook"></param>
        /// <returns></returns>
        [Route("api/treasure/addnode")]
        [HttpPost]
        public HttpResponseMessage PostAddNode(string jsonbook)
        {
            HttpResponseMessage result = null;           
            try
            {
                using (T_Model mode = new T_Model())
                {
                    book _book = Newtonsoft.Json.JsonConvert.DeserializeObject<book>(jsonbook);
                    if (_book != null)
                    {
                        mode.Books.Add(_book);
                        mode.SaveChanges();
                        result = new HttpResponseMessage(HttpStatusCode.OK);
                        result.Content = new StringContent("", Encoding.UTF8, "text/plain");
                        this.logger.Info("添加目录" + _book.b_name);
                    }
                    else
                    {
                        result = new HttpResponseMessage(HttpStatusCode.NotFound);
                        result.Content = new StringContent("", Encoding.UTF8, "text/plain");
                    }
                }

            }
            catch (Exception ex)
            {
                this.logger.Error("数据库连接出错：" + ex.Message);
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }

            return result;
        }
        /// <summary>
        /// 修改内容
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        [Route("api/treasure/updatecontent")]
        [HttpPost]
        public HttpResponseMessage PostUpdateContent([FromBody] string body)
        {
            HttpResponseMessage result = null;
            try
            {
                int id=Convert.ToInt32(HttpContext.Current.Request.Form["id"]);
                string content =  HttpContext.Current.Request.Form["content"];
                using (T_Model mode = new T_Model())
                {
                    book _book = mode.Books.FirstOrDefault(b => b.b_id == id);
                    if (_book != null)
                    {
                        _book.b_content = content;
                        mode.SaveChanges();
                        result = new HttpResponseMessage(HttpStatusCode.OK);
                        result.Content = new StringContent("", Encoding.UTF8, "text/plain");
                        this.logger.Info("修改目录" + _book.b_name + "内容");
                    }
                    else
                    {
                        result = new HttpResponseMessage(HttpStatusCode.NotFound);
                        result.Content = new StringContent("", Encoding.UTF8, "text/plain");
                    }
                }
            }
            catch (Exception ex)
            {
                this.logger.Error("数据库连接出错：" + ex.Message);
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }

            return result;
        }
        /// <summary>
        /// 修改目录名称
        /// </summary>
        /// <param name="body"></param>
        /// <returns></returns>
        [Route("api/treasure/updatenode")]
        [HttpPost]
        public HttpResponseMessage PostUpdateNode([FromBody] string body)
        {
            HttpResponseMessage result = null;
            try
            {
                int id = Convert.ToInt32(HttpContext.Current.Request.Form["id"]);
                string nodename = HttpContext.Current.Request.Form["nodename"];
                using (T_Model mode = new T_Model())
                {
                    
                        var _book = mode.Books.FirstOrDefault(b => b.b_id == id);
                    if (_book != null)
                    {
                        _book.b_name = nodename;
                        mode.SaveChanges();
                        result = new HttpResponseMessage(HttpStatusCode.OK);
                        result.Content = new StringContent("", Encoding.UTF8, "text/plain");
                        this.logger.Info("修改目录" + _book.b_name);
                    }
                    else
                    {
                        result = new HttpResponseMessage(HttpStatusCode.NotFound);
                        result.Content = new StringContent("", Encoding.UTF8, "text/plain");
                    }
                }
            }
            catch (Exception ex)
            {
                this.logger.Error("数据库连接出错：" + ex.Message);
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }

            return result;
        }
        /// <summary>
        /// 删除目录
        /// </summary>
        /// <param name="nodeid"></param>
        /// <returns></returns>
        [Route("api/treasure/deletenode")]
        [HttpPost]
        public HttpResponseMessage PostDeleteNode(int nodeid)
        {
            HttpResponseMessage result = null;
            try
            {
                using (T_Model mode = new T_Model())
                {
                    book _book = mode.Books.FirstOrDefault(b => b.b_id == nodeid);
                    if (_book != null)
                    {
                        mode.Books.Remove(_book);
                        mode.SaveChanges();
                        result = new HttpResponseMessage(HttpStatusCode.OK);
                        result.Content = new StringContent("", Encoding.UTF8, "text/plain");
                        this.logger.Info("删除目录" + _book.b_name);
                    }
                    else
                    {
                        result = new HttpResponseMessage(HttpStatusCode.NotFound);
                        result.Content = new StringContent("", Encoding.UTF8, "text/plain");
                    }
                }
            }
            catch (Exception ex)
            {
                this.logger.Error("数据库连接出错：" + ex.Message);
                return new HttpResponseMessage(HttpStatusCode.NotFound);
            }

            return result;
        }
    }
}
